var randomid = "question1";
var id = "question1";
var answers = [ ];
var question = "";
var correctAnswer = 2;
var explanation = "";
var submissions = 2;
var resourcesLocation = 'https://blog-questions.googlecode.com/git/version1/';



/**
 * Get the number of answers at the moment
 */

function getNumberAnswers(answers)
{
	var childs = answers.getElementsByTagName('label');
	return childs.length;
}


/**
 * Create an answer node type
 */
function createAnswer(numberAnswers)
{
	var answer = document.createElement('DIV');
	answer.className = "form-group";
	var contents = '<label for="answer?" class="col-sm-3 control-label">Answer ?:</label>' + 
			     '<div class="col-sm-9">' +
			     '<textarea name="answer?" cols="55" rows="4" class="form-control" id="answer?" placeholder="insert answer"></textarea>' +
			     '</div>';
	var answerContents = contents.replace(/\?/g,numberAnswers + 1);
	answer.innerHTML = answerContents;
	return answer;
	
}

/**
 * Create new option
 */
function createOption(value,text)
{
	var option = document.createElement('OPTION');
	var text = document.createTextNode(text);
	option.appendChild(text);
	option.value = value;
	return option;
}

/**
 * Add an extra textarea answer slot at the end
 */
function addAnswer()
{	
	var answers = document.getElementById('answers');
	var numberAnswers = getNumberAnswers(answers);

	// Add new answer to answers
	var answer = createAnswer(numberAnswers);
	answers.appendChild(answer);

	// Update the number of answers
	numberAnswers++;

	// Get definitions
	var definitions = document.getElementById('definitions');

	// Get the two select definitions
	var definitionsGroup = definitions.getElementsByTagName('select');

	// Add correct answer alternative
	var alternativeAnswer = createOption(numberAnswers - 1,'Answer ' + numberAnswers);
	definitionsGroup[0].appendChild(alternativeAnswer);

	// Add possible number of possible submissions alternative
	var alternativeNumberSubmissions = createOption(numberAnswers - 1,(numberAnswers - 1) + ' submissions');
	definitionsGroup[1].appendChild(alternativeNumberSubmissions); 
	
	return false;
}

/**
 * Attaches the addAnswer function to the plus sign onclick event
 */
function attachAddAnswer()
{
	var controlAnswers = document.getElementById('answerscontrols');
	var childs = controlAnswers.getElementsByTagName('a');
	childs[1].onclick = addAnswer;
	
}

function removeNumberSubmissions(set)
{
	lastChild = set.lastChild;
	if (lastChild.selected)
	{
		lastChild.previousSibling.selected = "selected";
	}
	set.removeChild(set.lastChild);
}


/**
 * remove bigger number of submissions, select previous option if bigger is selected
 */
function removeAnswer()
{
	var answers = document.getElementById('answers');
	var numberAnswers = getNumberAnswers(answers);

	// Original number of answers, do nothing
	if (numberAnswers < 3)
	{
		return false;
	}

	// Remove last child;
	answers.removeChild(answers.lastChild);

	// Update the number of answers
	numberAnswers--;

	// Get definitions
	var definitions = document.getElementById('definitions');

	// Get the two select definitions
	var definitionsGroup = definitions.getElementsByTagName('select');

	definitionsGroup[0].removeChild(definitionsGroup[0].lastChild);

	// propely remove bigger number of submissions
	removeNumberSubmissions(definitionsGroup[1]);
	
	return false;
}
	
function attachRemoveAnswer()
{
	var controlAnswers = document.getElementById('answerscontrols');
	var childs = controlAnswers.getElementsByTagName('a');
	childs[0].onclick = removeAnswer;
}

/**
 * Fills up the variables used for question creation
 */
function fillUpVariables()
{
	question = document.getElementById('question').getElementsByTagName('textarea')[0].value.trim();
	question = question.replace(/\r\n|\r|\n/g,"<br />");
	// text = text.replace(/\\/g,"\\");
	question = question.replace(/\"/g,"\\\"");
	
	// Fills up answers array
	var answer = '';
	answers = [];
	answerNodes = document.getElementById('answers').getElementsByTagName('textarea');
	for (var i = 0, length = answerNodes.length; i < length; i++)
	{
		answer = answerNodes[i].value.trim();
		answer = answer.replace(/\r\n|\r|\n/g,"<br />");
		answer = answer.replace(/\"/g,"\\\"");
		answers.push(answer);
	}

	var definitions = document.getElementById('definitions').getElementsByTagName('select');
	// Correct answer
	correctAnswer = definitions[0].value;

	// Submissions
	submissions = definitions[1].value;

	// Explanation
	explanation = document.getElementById('explanation').getElementsByTagName('textarea')[0].value.trim();
	
	// Random id
	randomid = 'question' + Math.floor((Math.random() * 100000) + 1); 
}

function array2string(array)
{
	var string = '[';
	for (var i = 0, length = array.length; i < length; i++)
	{
		
		if (i != 0)
		{
			string += ',';
		}
		string += ' ' + '"' + array[i] + '"';
	}
	string += ' ]';
	return string;
}


/**
 * Show the code to be inserted in the blog
 */
function showCode()
{
	var code = document.getElementById('code');
	var text = '<p> Choose to edit the html code of your post.</p>'
		+  '<p> Insert the following code at the end of your post: </p>' 
		+  '&lt;link href="https://blog-questions.googlecode.com/git/version1/question-1.0.css" type="text/css" rel="stylesheet"&gt; <br />'
		+  '&lt;script type="text/javascript" src="https://blog-questions.googlecode.com/git/version1/question-1.0.js"&gt;&lt;/script\&gt; <br />'
		+  '&lt;script&gt; var id = "' + randomid + '";<br />var answers = ' + array2string(answers) + ';<br />'
		+  'var question = "' + question + '";<br />var correctAnswer = ' + correctAnswer + ';<br />'
		+  'var submissions = ' + submissions + ';<br />' + 'var explanation = "' + explanation + '";<br />'
		+  'var resourcesLocation = "https://blog-questions.googlecode.com/git/version1/";<br />'
		+  'createQuestion();<br />'
		+  '&lt;/script&gt;'
		+  '<br /><p> Insert the following code where you want the question to show up:</p>'
		+  '&lt;div class="question" id="' + randomid + '"&gt'
        	+  '&lt;/div&gt';


	code.innerHTML = text;
}


/**
 * If form is filled up then show the copy past code
 */
function createQuestionCode()
{
	var valid = true;
	var texts = document.getElementsByTagName('textarea');
	for (var i = 0, length = texts.length - 1; i < length; i++)
	{
		if (texts[i].value.trim() == '')
		{
			valid = false;
			break;
		}
	}
	
	var code = document.getElementById('code');
	var example = document.getElementById('question1');
	
	if (valid == false)
	{
		code.innerHTML = '<span class="alert">Warning: there is at least one required field to be filled</span>';
		example.innerHTML = '';	
	}
	else
	{
		code.innerHTML ='';
		fillUpVariables();
		showCode();
		// show question example
		example.innerHTML = '';	
		createQuestion();
	}

	window.location = '#code';
	return false;
}


function attachCreateQuestionCode()
{
	var form = document.getElementById('questionform');
	form.onsubmit = createQuestionCode;
}


window.onload = function() { attachAddAnswer(); attachRemoveAnswer(); attachCreateQuestionCode(); }

